package com.qingcloud.common.auth.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.qingcloud.base.api.remote.admin.AdminApi;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.pojo.AjaxResult;
import com.qingcloud.base.pojo.PriResult;
import com.qingcloud.base.remote.pojo.OrderParam;
import com.qingcloud.base.remote.pojo.SysOrderDTO;
import com.qingcloud.base.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/oauth")
public class OauthController {
    @Autowired
    @Lazy
    private TokenStore tokenStore;
    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private AdminApi adminApi;

    /**
     * 重写login接口
     */
    @PostMapping("/token")
    public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
                                                             @RequestParam Map<String, String> parameters, HttpServletResponse response) throws HttpRequestMethodNotSupportedException {
        //账号密码登录情况，解密登录参数
        if (StrUtil.isNotBlank(parameters.get("password"))) {
            String username = Base64.decodeStr(parameters.get("username"), StandardCharsets.UTF_8);
            String password = Base64.decodeStr(parameters.get("password"), StandardCharsets.UTF_8);
            parameters.put("username", username);
            parameters.put("password", password);
        }

        ResponseEntity<OAuth2AccessToken> auth2AccessTokenResponseEntity = tokenEndpoint.postAccessToken(principal, parameters);
        PriResult priResult = (PriResult) auth2AccessTokenResponseEntity.getBody();
        OAuth2AccessToken accessToken = (OAuth2AccessToken) priResult.getDatas();
        Map<String, Object> map = accessToken.getAdditionalInformation();
        String userId = (String) map.get(SecurityConstants.LOGIN_USER_PARAM_USERID);
        String userName = (String) map.get(SecurityConstants.LOGIN_USER_PARAM_USERNAME);
        //更新登录状态
        AjaxResult ajaxResult = adminApi.loginStatus(userId);
        log.info("{} update login status result {}", userId, ajaxResult.isSuccessful());
        // 用户名ID
        CookieUtil.addCookie(response, CookieUtil.USER_ID_KEY, userId, 0);
        // 用户名
        CookieUtil.addCookie(response, CookieUtil.USER_NAME_KEY, userName, 0);
        // 组织ID
        CookieUtil.addCookie(response, CookieUtil.ORG_KEY, (String) map.get(SecurityConstants.LOGIN_USER_PARAM_ORG_ID), 0);
        //用户默认订单
        OrderParam orderParam = new OrderParam();
        orderParam.setUserId(userId);
        orderParam.setBusinessTypes("3");
        List<SysOrderDTO> orders = adminApi.getOrders(orderParam);
        if (CollUtil.isNotEmpty(orders)) {
            CookieUtil.addCookie(response, CookieUtil.PROJECT_KEY, orders.get(0).getOrderId(), 0);
        }
        return auth2AccessTokenResponseEntity;
    }
}
